package com.erp.freight.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.erp.freight.domain.fpx.*;
import com.ruoyi.order.api.domain.OrderStatusParam;
import com.erp.freight.service.IFpxLogisticsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fpx.api.constants.AmbientEnum;
import com.fpx.api.model.AffterentParam;
import com.fpx.api.utils.ApiHttpClientUtils;
import com.ruoyi.ae.api.RemoteAeOrderAddrService;
import com.ruoyi.ae.api.RemoteAeOrderService;
import com.ruoyi.ae.api.domain.AeStoreOrderReceiptAddress;
import com.ruoyi.ae.api.domain.AeWarehouseOrderInfo;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.ExpenseType;
import com.ruoyi.common.core.enums.FlowType;
import com.ruoyi.common.core.enums.PayType;
import com.ruoyi.common.core.utils.DingDingPushUtil;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.gather.api.RemoteCollectProductSkuService;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import com.ruoyi.order.api.RemoteErpChildOrderService;
import com.ruoyi.order.api.RemoteErpOrderLogService;
import com.ruoyi.order.api.RemoteErpOrderService;
import com.ruoyi.order.api.RemoteEvaluationService;
import com.ruoyi.order.api.domain.ErpSellerChildOrder;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerStoreProductEvaluation;
import com.ruoyi.statistics.api.RemoteOrderStatisticsService;
import com.ruoyi.statistics.api.domain.ErpOrderInfoStatistics;
import com.ruoyi.system.api.RemoteDictDataService;
import com.ruoyi.wallet.api.RemoteWalletService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FPX仓储信息Service业务层处理
 *
 * @author erp
 * @date 2023-03-28
 */
@RequiredArgsConstructor
@Service
public class FpxLogisticsServiceImpl implements IFpxLogisticsService {
    
    public static String FPS_APP_KEY = "d8ccd4bb-0a39-4cd1-87c2-f5cce0fb323d";
    public static String FPS_APP_SECRET = "f3166d57-ce09-4cff-9b6f-8c96734945a7";
//    private final ErpSellerOrderMapper sellerOrderMapper;
//    private final ErpCollectProductExpandMapper collectProductExpandMapper;
//    private final ErpSellerChildOrderMapper sellerChildOrderMapper;
//    private final ErpSellerStoreNotautoProductSkuMapper erpSellerStoreNotautoProductSkuMapper;
//    private final ErpSellerStoreProductEvaluationMapper evaluationMapper;
//    private final ErpCollectProductSkuMapper collectProductSkuMapper;
//    private final IErpCollectProductSkuService collectProductSkuService;
//    private final IErpCollectProductService collectProductService;
    private final RemoteWalletService remoteWalletService;
//    private final ErpSellerStoreProductMapper sellerStoreProductMapper;
//    private final IErpOrderInfoStatisticsService orderInfoStatisticsService;
//    private final ErpSellerOrderExtendMapper erpSellerOrderExtendMapper;
//    private final ErpSellerOrderMapper erpSellerOrderMapper;
//    private final ErpSellerStoreEmpowerMapper erpSellerStoreEmpowerMapper;
    private final RemoteErpOrderService remoteErpOrderService;
    private final RemoteErpChildOrderService remoteErpChildOrderService;
    private final RemoteErpOrderLogService remoteErpOrderLogService;
    private final RemoteEvaluationService evaluationService;
    private final RemoteOrderStatisticsService orderInfoStatisticsMapper;
    private final RemoteCollectProductSkuService remoteCollectProductSkuService;
    private final RemoteCollectProductService remoteCollectProductService;
    private final RemoteAeOrderAddrService remoteAeOrderAddrService;
    private final RemoteDictDataService remoteDictDataService;
    private final RemoteAeOrderService remoteAeOrderService;

    @Override
    @Transactional
    //TODO 自动提交订单
    public R<Object> autoSubmitForReview() {
//        List<String> autoStoreList = erpSellerStoreEmpowerMapper.selectAutoStoreList();
//        List<ErpSellerOrder> orderSelList = erpSellerOrderMapper.selectAutoStoreOrderList(autoStoreList);
////        for (String cnName : map.keySet()) {
//        Boolean flag = false;
//        for (ErpSellerOrder order : orderSelList) {
//            ErpSellerStoreEmpower empower = erpSellerStoreEmpowerMapper.selectEmpowerByUserName(order.getSellerLoginId());
//            if (ObjectUtils.isNull(empower)) {
//                continue;
//            }
//            //取自动化绑定的用户
////            Long userId = map.get(cnName);
//            //取店铺绑定erp用户
//            Long userId = empower.getUserId();
//            //找到所有可提交审核的订单，去提
//            OrderStatusParam param = new OrderStatusParam();
//            ErpSellerOrderExtend extend = erpSellerOrderExtendMapper.selectOne(
//                    new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, order.getOrderId())
//            );
//
//            //错误类型
//            String errorReason = null;
//            if (ObjectUtils.isNull(extend)) {
//                errorReason = "订单延伸表数据为空";
//                flag = true;
//            } else {
//                //如果已经提交过，则不再提交
//                if (ObjectUtils.isNotNull(extend.getIsAutoOrder())) {
//                    continue;
//                }
//                param.setOrderId(order.getOrderId());
//                param.setErpInnerOrderStatus("103");
//                param.setType(0);
//                param.setUserId(userId);
//
//                try {
//                    R<Object> objectR = submitForReviewByAuto(param);
//                    if (objectR.getCode() == 200) {
//                        extend.setIsAutoOrder(1);
//                        erpSellerOrderExtendMapper.updateById(extend);
//                    } else {
//                        flag = true;
//                        //失败
//                        extend.setIsAutoOrder(0);
//                        extend.setFailedSubmitReason((Integer) objectR.getData());
//                        errorReason = (String) objectR.getMsg();
//                        erpSellerOrderExtendMapper.updateById(extend);
//                    }
//                } catch (Exception e) {
//                    flag = true;
//                    errorReason = "其他原因异常结束";
//                    //失败
//                    extend.setIsAutoOrder(0);
//                    extend.setFailedSubmitReason(3);
//                    erpSellerOrderExtendMapper.updateById(extend);
//                }
//            }
//
//            if (flag) {
//                System.out.println("提交订单" + extend.getOrderId() + "异常");
//                //钉钉提醒
//                StringBuffer pushSb = new StringBuffer();
//                pushSb.append("订单自动提交异常 @李烁 ：")
//                        .append("订单店铺 :" + empower.getStoreUserName() + "||")
//                        .append("订单id :" + order.getOrderId())
//                        .append("失败原因：" + errorReason);
//                DingDingPushUtil.send(pushSb.toString());
//                flag = false;
//            }
//        }
        return R.ok("自动提交完成");
    }


    @Override
    @Transactional
    public R<Object> submitForReview(OrderStatusParam param) {
        Integer type = param.getType();
        Long userId = param.getUserId();
        String remark = null;
        List<Long> orderIds = param.getOrderIds();
        for (Long orderId : orderIds) {
            ErpSellerOrder erpSellerOrder = remoteErpOrderService.getInfoByOrderId(orderId);
            if (ObjectUtils.isNotNull(type) && type == 0) {
                remark = "该订单为系统自动化提交";
            } else {
                remark = "该订单为主动提交";
            }

            // 判断订单是否已提交审核
            if (!erpSellerOrder.getErpInnerOrderStatus().equals("101")) {
                continue;
            }
            // 判断发货仓是否设置 暂时屏蔽，不管是否用菜鸟
//            List<AeLogisticsServiceName> aeLogisticsServiceNameList = new ArrayList<>();
//            try {
//                aeLogisticsServiceNameList = iErpSellerOrderService.logisticsServiceQueryOld(orderId,
//                        erpSellerOrder.getSellerLoginId());
//            } catch (Exception e) {
//                return R.fail("您未设置系统推荐发货仓或该sku信息异常");
//            }
//            if (aeLogisticsServiceNameList.size() == 0) {
//                return R.fail("您未设置系统推荐发货仓");
//            }
            List<ErpSellerChildOrder> childOrderList = remoteErpChildOrderService.getChildByOrder(orderId);
            BigDecimal totalAmount = BigDecimal.ZERO; // 扣款金额
            R<Object> byOrderId = orderInfoStatisticsMapper.getByOrderId(orderId.toString());
            ErpOrderInfoStatistics orderInfoStatistics = JSONObject.parseObject(JSONObject.toJSONString(byOrderId.getData()), ErpOrderInfoStatistics.class);
            if (orderInfoStatistics == null || orderInfoStatistics.getPurchaseCost() == null) {
                return R.fail("该商品没有采购价格,暂时无法提交审核,请稍后再试");
            }
            totalAmount = new BigDecimal(orderInfoStatistics.getPurchaseCost());
            if (totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
                return R.fail("该商品没有采购价格,暂时无法提交审核,请稍后再试");
            }
            R<Object> returnR = remoteWalletService.updateWallet(FlowType.DEDUCTION.getCode(),
                    ExpenseType.ORDERPAYMENT.getCode(), PayType.YE.getCode(), totalAmount, userId, orderId.toString(), remark);
            if (returnR.getCode() == 200) {
                for (ErpSellerChildOrder erpSellerChildOrder : childOrderList) {
                    // 获取sku信息
                    String skuCode = erpSellerChildOrder.getSkuCode();

                    // 创建sku
                    String createSkuReturn = createSku(skuCode, erpSellerChildOrder.getProductCurrencyCode(), erpSellerChildOrder.getProductPrice());
                    if (createSkuReturn != null) {
                        JSONObject skuJsonObject = JSONObject.parseObject(createSkuReturn);
                        if ("0".equals(skuJsonObject.getString("result"))) {
                            throw new RuntimeException(skuJsonObject.getJSONArray("errors").toString());
                        }
                    }

                    // 状态设为订单待采购
                    remoteErpOrderLogService.createOrderLog(orderId, null, OrderLogType.SubmitOrder, remark,
                            OrderProcessFlag.Begin.getInfo(), "103");
                    remoteErpOrderService.setInnerStatus(orderId, "103", OrderProcessFlag.Begin.getInfo());
                    StringBuffer pushSb = new StringBuffer();

                    // 判断是否是公司测评单
                    ErpSellerStoreProductEvaluation productEvaluation = evaluationService.getEvaluationByOrderId(orderId);
                    if (productEvaluation != null && productEvaluation.getType() == 1) {
                        remoteErpOrderLogService.createOrderLog(orderId, null, OrderLogType.HasBeenPurchase,
                                null, OrderProcessFlag.CompanyEva.getInfo(), "105");
                        remoteErpOrderService.setInnerStatus(orderId, "105", "companyEva");
                    } else {
                        pushSb.append("有新的店铺提交待审核订单 ：")
                                .append("\n")//换行
                                .append("订单店铺 :" + erpSellerOrder.getSellerLoginId() + "(" + erpSellerOrder.getSellerSignerFullname() + ")")
                                .append("\n")//换行
                                .append("订单id :" + orderId);
                        try {
                            DingDingPushUtil.sendBySginTianZai(pushSb.toString(),"孙");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                return returnR;
            }
        }
        return R.ok(remark);
    }

    /*public R<Object> submitForReviewByAuto(OrderStatusParam param) {
        Long orderId = param.getOrderId();
        Long userId = param.getUserId();
        String remark = null;
        List<Long> orderIds = param.getOrderIds();
        ErpSellerOrder erpSellerOrder = remoteErpOrderService.getInfoByOrderId(orderId);
        remark = "该订单为系统自动化提交";
        List<ErpSellerChildOrder> childOrderSelList = remoteErpChildOrderService.getChildByOrder(orderId);
        List<String> skuCodeList = childOrderSelList.stream()
                .map(ErpSellerChildOrder::getSkuCode)
                .collect(Collectors.toList());

        List<ErpSellerStoreNotautoProductSku> notAutoProductSkuSelList = erpSellerStoreNotautoProductSkuMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreNotautoProductSku>()
                        .eq(ErpSellerStoreNotautoProductSku::getStoreAlias, erpSellerOrder.getSellerLoginId())
        );
        List<String> notAutoSkuCodeList = notAutoProductSkuSelList.stream()
                .map(ErpSellerStoreNotautoProductSku::getSkuCode)
                .collect(Collectors.toList());

        List<String> checkNewListA = new ArrayList<>(skuCodeList);
        // 保留在listB中也存在的元素
        checkNewListA.retainAll(notAutoSkuCodeList);
        // 如果tempListA现在不为空，说明有交集
        boolean flag = !checkNewListA.isEmpty();
        if (flag) {
            return R.fail("有不自动提交的sku设置");
        }

        // 判断订单是否已提交审核
        if (!erpSellerOrder.getErpInnerOrderStatus().equals("101")) {
            return R.fail("订单当前不为待提交审核状态", 1);
        }
        //TODO 有可能发延津骏捷，不进行判断
//        // 判断发货仓是否设置
//        List<AeLogisticsServiceName> aeLogisticsServiceNameList = new ArrayList<>();
//        try {
//            aeLogisticsServiceNameList = iErpSellerOrderService.logisticsServiceQueryOld(orderId,
//                    erpSellerOrder.getSellerLoginId());
//        } catch (Exception e) {
//            return R.fail("您未设置系统推荐发货仓或该sku信息异常", 2);
//        }
//        if (aeLogisticsServiceNameList.size() == 0) {
//            return R.fail("您未设置系统推荐发货仓", 3);
//        }
        List<ErpSellerChildOrder> childOrderList = sellerChildOrderMapper.selectList(
                new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, orderId));
        BigDecimal totalAmount = BigDecimal.ZERO; // 扣款金额
//            for (ErpSellerChildOrder erpSellerChildOrder : childOrderList) {
//                // 扣款
//                String childOrderId = erpSellerChildOrder.getChildOrderId();
//                ErpChildOrderStatistics statistics = childOrderStatisticsMapper.selectOne(new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getChildOrderId, childOrderId));
//                // 统计表里获取采购成本
//                if (ObjectUtils.isEmpty(statistics)) {
//                    return R.fail("该商品没有采购价格,暂时无法提交审核,请稍后再试");
//                }else {
//                    // 取出子订单的采购成本相加进行扣款
//                    String purchaseCost = statistics.getCostTotalPrice();
//                    if (StringUtils.isEmpty(purchaseCost)) {
//                        return R.fail("该商品没有采购价格,暂时无法提交审核,请稍后再试");
//                    }
//                    totalAmount = totalAmount.add(new BigDecimal(purchaseCost));
//                }
//            }
        //创建采购价
        orderInfoStatisticsService.saveOrderProfitInfo(erpSellerOrder);
        ErpOrderInfoStatistics orderInfoStatistics = orderInfoStatisticsMapper.selectOne(new LambdaQueryWrapper<ErpOrderInfoStatistics>()
                .eq(ErpOrderInfoStatistics::getOrderId, orderId));
        if (orderInfoStatistics == null || orderInfoStatistics.getPurchaseCost() == null) {
            return R.fail("该商品没有采购价格,暂时无法提交审核,请稍后再试", 4);
        }
        totalAmount = new BigDecimal(orderInfoStatistics.getPurchaseCost());
        if (totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return R.fail("该商品没有采购价格,暂时无法提交审核,请稍后再试", 4);
        }
        R<Object> returnR = iErpSellerStoreWalletService.updateWallet(FlowType.DEDUCTION.getCode(),
                ExpenseType.ORDERPAYMENT.getCode(), PayType.YE.getCode(), totalAmount, userId, orderId.toString(), remark);
        if (returnR.getCode() == 200) {
            for (ErpSellerChildOrder erpSellerChildOrder : childOrderList) {
                // 获取sku信息
                String skuCode = erpSellerChildOrder.getSkuCode();

                // 创建sku
                String createSkuReturn = createSku(skuCode, erpSellerChildOrder.getProductCurrencyCode(), erpSellerChildOrder.getProductPrice());
                if (createSkuReturn != null) {
                    JSONObject skuJsonObject = JSONObject.parseObject(createSkuReturn);
                    if ("0".equals(skuJsonObject.getString("result"))) {
                        throw new RuntimeException(skuJsonObject.getJSONArray("errors").toString());
                    }
                }

                // 状态设为订单待采购
                orderLogService.createOrderLog(orderId, null, OrderLogType.SubmitOrder, remark,
                        OrderProcessFlag.Begin.getInfo(), "103");
                iErpSellerOrderService.setInnerStatus(orderId, "103", OrderProcessFlag.Begin.getInfo());
                StringBuffer pushSb = new StringBuffer();

                // 判断是否是公司测评单
                ErpSellerStoreProductEvaluation productEvaluation = evaluationMapper
                        .selectOne(new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>()
                                .eq(ErpSellerStoreProductEvaluation::getOrderId, orderId)
                                .eq(ErpSellerStoreProductEvaluation::getType, 1));
                if (productEvaluation != null) {
                    orderLogService.createOrderLog(orderId, null, OrderLogType.HasBeenPurchase,
                            null, OrderProcessFlag.CompanyEva.getInfo(), "105");
                    iErpSellerOrderService.setInnerStatus(orderId, "105", "companyEva");
                } else {
                    pushSb.append("有新的自动化店铺提交待审核订单 @朱孟飞 ：")
                            .append("订单店铺 :" + erpSellerOrder.getSellerLoginId() + "(" + erpSellerOrder.getSellerSignerFullname() + ")   ||    ")
                            .append("订单id :" + orderId);
                    DingDingPushUtil.send(pushSb.toString());
                }
            }
        } else {
            returnR.setData(5);
            return returnR;
        }
        return R.ok(remark);
    }*/

    /**
     * 创建sku
     */
    @Override
    public String createSku(String skuCode, String productCurrencyCode, String productPrice) {
        AffterentParam publicParam = new AffterentParam();
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setVersion("1.0.0");
        publicParam.setLanguage("CN");
        publicParam.setMethod("fu.wms.sku.getlist");
        
        ErpCollectProductSku productSku = new ErpCollectProductSku();
        productSku.setSkuCode(skuCode);
        List<ErpCollectProductSku> collectProductSkuList = remoteCollectProductSkuService.getCollectProductSkuList(productSku);
        ErpCollectProductSku skuInfo = collectProductSkuList.get(0);
        List<String> skuCodeList = new ArrayList<>();// 存放skuCode,用来查询是否需要创建sku
        skuCodeList.add(skuCode);
        String skuByCode = getSkuByCode(skuCodeList, publicParam);
        JSONArray isSkuCode = JSONObject.parseObject(skuByCode).getJSONObject("data")
                .getJSONArray("skulist");
        // 没有则创建sku
        if (isSkuCode == null || isSkuCode.size() == 0) {
            CreateSku createSku = new CreateSku();
            Declare_country_list declare_countryList = new Declare_country_list();
            ArrayList<Declare_country_list> declare_countryLists = new ArrayList<>();

            Long collectProductId = skuInfo.getCollectProductId();
            ErpCollectProductExpand searchProductExpand = new ErpCollectProductExpand();
            searchProductExpand.setCollectProductId(collectProductId);
            R<Object> productExpandInfo = remoteCollectProductService.getCollectProductExpandInfo(searchProductExpand);
            ErpCollectProductExpand erpCollectProductExpand = JSONObject.parseObject(JSON.toJSONString(productExpandInfo.getData()), ErpCollectProductExpand.class);
            if (erpCollectProductExpand == null) {
                throw new RuntimeException("获取商品信息异常");
            }
            String hsCode = erpCollectProductExpand.getHsCode();// 代表海关编码表的主键
            createSku.setSku_code(skuCode);
            Map<String, Object> categoryMap = remoteCollectProductService.getCategoryByCollectId(collectProductId);
            String categoryEn = (String) categoryMap.get("categoryEn");
            String categoryCN = (String) categoryMap.get("categoryCN");

            // 获取商品规格
            R<Object> specBySkuCdeNew = remoteCollectProductSkuService.getSpecBySkuCodeNew(skuCode);
            String specBySkuCde = JSONObject.toJSONString(specBySkuCdeNew.getData());
            if (StringUtils.isNotEmpty(specBySkuCde)) {
                String temp = "";
                temp = categoryCN + " " + specBySkuCde;
                if (temp.length() < 100) {
                    categoryCN = temp;
                }
            }
            createSku.setSku_name(categoryEn);
            createSku.setChinese_name(categoryCN);
            String skuBuyLink = skuInfo.getSkuBuyLink();
            if (skuBuyLink != null && skuBuyLink.startsWith("http")) {
                createSku.setSales_link(skuBuyLink);
            }
            createSku.setWeight(skuInfo.getSkuWeight());
            createSku.setLength(skuInfo.getSkuLength().doubleValue());
            createSku.setWidth(skuInfo.getSkuWidth().doubleValue());
            createSku.setHeight(skuInfo.getSkuHeight().doubleValue());
            createSku.setSpecification("一件代发");
            String skuImage = skuInfo.getSkuImage();
            if (skuImage != null) {
                List<String> imgList = new ArrayList<>();
                if (!skuImage.startsWith("http")) {
                    skuImage = "https://file.pbb2c.com/" + skuImage;
                }
                imgList.add(skuImage);
                createSku.setPicture_url(imgList);
            }
            declare_countryList.setExport_declare(categoryEn);
            declare_countryList.setExport_declare_value(productPrice);
            declare_countryList.setExport_currency(productCurrencyCode);
            declare_countryList.setExport_hscode(hsCode);
            declare_countryList.setCountry("CN");
            declare_countryList.setExport_country("CN");
            declare_countryList.setImport_declare(categoryEn);
            declare_countryList.setDeclare_value(productPrice);
            declare_countryList.setCurrency(productCurrencyCode);
            declare_countryList.setHs_code(hsCode);
            declare_countryLists.add(declare_countryList);
            createSku.setDeclare_country_list(declare_countryLists);
            JSONObject createSkuJson = null;
            try {
                createSkuJson = JSONObject.parseObject(new JsonMapper().writeValueAsString(createSku));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            publicParam.setMethod("fu.wms.sku.newcreate");
            String createSkuReturn = ApiHttpClientUtils.apiJsongPost(publicParam, createSkuJson,
                    AmbientEnum.FORMAT_ADDRESS);
            JSONObject skuJsonObject = JSONObject.parseObject(createSkuReturn);
            if ("0".equals(skuJsonObject.getString("result"))) {
                throw new RuntimeException(skuJsonObject.getJSONArray("errors").toString());
            }
            return createSkuReturn;
        } else {
            return null;
        }
    }


    /**
     * 根据sku_code查找sku
     */
    @Override
    public String getSkuByCode(List<String> skuCode, AffterentParam publicParam) {
        Map<String, Object> skuCodeMap = new HashMap<>();
        skuCodeMap.put("lstsku", skuCode);
        publicParam.setMethod("fu.wms.sku.getlist");
        return ApiHttpClientUtils.apiJsongPost(publicParam, skuCodeMap, AmbientEnum.FORMAT_ADDRESS);
    }

    @Override
    public String createOrderFPX(Long orderId) {

        List<ErpSellerChildOrder> childOrderList = remoteErpChildOrderService.getChildByOrder(orderId);

        AffterentParam publicParam = new AffterentParam();
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setVersion("1.0.0");
        publicParam.setLanguage("CN");
        publicParam.setMethod("fu.wms.outbound.create");
        JsonMapper jsonMapper = new JsonMapper();

        List<Oconsignment_sku> oconsignmentSkuses = new ArrayList<>();
        Oconsignment_sku oconsignmentSku = new Oconsignment_sku();

        for (ErpSellerChildOrder childOrder : childOrderList) {
            String skuCode = childOrder.getSkuCode();
            Long productCount = childOrder.getProductCount();
            // 出库的商品信息
            oconsignmentSku.setStock_quality("G");
            oconsignmentSku.setSku_code(skuCode);
            oconsignmentSku.setQty(productCount.intValue());
            oconsignmentSkuses.add(oconsignmentSku);
            oconsignmentSku = new Oconsignment_sku();
        }
        // 创建出库委托
        CreateOutBound createOutBound = new CreateOutBound();
        createOutBound.setRef_no(orderId.toString());
        createOutBound.setFrom_warehouse_code("CNDGMB");
        createOutBound.setConsignment_type("S");

        AeStoreOrderReceiptAddress address = remoteAeOrderAddrService.getAddressByOrderId(orderId);

        Supplier_address supplierAddress = new Supplier_address();
        String country = address.getCountry();
//        if (country.equals("UK")) {
//            country = "GB";
//        }
        // 如果国家编码是SRB,转为RS
        R<String> countryCodeR = remoteDictDataService.getDictLabel("ae_country_code", country, SecurityConstants.INNER);
        String countryCode = JSONObject.toJSONString(countryCodeR.getData());
        if (StringUtils.isNotEmpty(countryCode)) {
            country = countryCode;
        }
        supplierAddress.setCountry(country);
        supplierAddress.setState(address.getProvince());
        supplierAddress.setCity(address.getCity());
        supplierAddress.setPost_code(address.getZip());
        supplierAddress.setStreet(address.getDetailAddress());
        String house = address.getAddress() != null ? address.getAddress() : "" + address.getAddress2();
        if (house.length() < 128) { // 门牌号太长,不传了
            supplierAddress.setHouse_number(house);
        }
        supplierAddress.setFirst_name(address.getContactPerson());
        supplierAddress.setPhone(address.getPhoneNumber());

        createOutBound.setOconsignment_desc(supplierAddress);
        createOutBound.setOconsignment_sku(oconsignmentSkuses);
        Logistics_service_info logistics_serviceInfo = new Logistics_service_info();
        
        AeWarehouseOrderInfo aeWarehouseOrderInfo = remoteAeOrderService.getOnlineLogisticsLabel(orderId);

        String onlineLogisticsLabel = aeWarehouseOrderInfo.getOnlineLogisticsLabel(); // 线上物流发货面单
        createOutBound.setShippinglabel(onlineLogisticsLabel);
        logistics_serviceInfo.setLogistics_product_code("B068");
        String intlTrackingNo = aeWarehouseOrderInfo.getIntlTrackingNo(); // 线上发货国际单号
        createOutBound.setShipping_no(intlTrackingNo);
        
        logistics_serviceInfo.setPrint_delivery("N");
        createOutBound.setLogistics_service_info(logistics_serviceInfo);
        JSONObject outBoundJson = null;
        try {
            outBoundJson = JSONObject.parseObject(jsonMapper.writeValueAsString(createOutBound));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        String s1 = ApiHttpClientUtils.apiJsongPost(publicParam, outBoundJson, AmbientEnum.FORMAT_ADDRESS);
        JSONObject jsonObject = JSONObject.parseObject(s1);

        if ("0".equals(jsonObject.getString("result"))) { // 创建出库委托失败
            throw new RuntimeException("订单号：" + orderId + "出库委托创建失败，原因是：" +
                    jsonObject.getJSONArray("errors").getJSONObject(0)
                            .getString("error_msg"));
        }
        String consignmentNo = jsonObject.getJSONObject("data").getString("consignment_no");
        // 获取到该订单的仓储发货记录
//        FpxWarehousRecord record = warehousRecordMapper.selectOne(new LambdaQueryWrapper<FpxWarehousRecord>()
//                .eq(FpxWarehousRecord::getRefNo, orderId.toString())
//                .eq(FpxWarehousRecord::getStatus, 2));
//        if (record != null) {
//            record.setConsignmentNo(consignmentNo);
//            warehousRecordMapper.updateById(record);
//        }
        return consignmentNo;
    }
}
